<?php

class ArticleController extends Controller
{
	public function filters()
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	public function accessRules()
	{
		return array(
			array('deny',
				'users'=>array('?'),
			),
		);
	}

	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}

	public function actionCreate()
	{
        $model=new Article();

        // 设置单选按钮默认值
        $model->article_is_top = 1;

        $this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
			$model->attributes=$_POST['Article'];

            $this->upAndThumb($model);

			if($model->save())
                BlogTool::successRedirect('成功添加文章', 'article/index');
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

        // 设置checkbox默认值
        $model->article_tag = explode(',', $model->article_tag);

        $this->performAjaxValidation($model);

		if(isset($_POST['Article']))
		{
            $model->attributes=$_POST['Article'];

            // 是否有上传行为
            if(CUploadedFile::getInstance($model, 'article_thumbnail'))
                $this->upAndThumb($model);

			if($model->save())
                BlogTool::successRedirect('成功修改文章', 'article/index');
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	public function actionDelete($id)
	{
        $this->loadModel($id)->delete();
        BlogTool::successRedirect('成功删除文章', 'article/index');
	}

	public function actionIndex()
	{
		$model = new Article();

        $criteria = new CDbCriteria();
        $criteria->select = 'id, article_title, article_nav, article_tag, article_admin, article_date';
        $criteria->order = 'article_date desc';

        $pager = parent::showPager($model, $criteria);

        $data = $model->findAll($criteria);

        // 获取栏目和标签名称
        $nav = new Nav();
        $tags = new Tags();
        $tagCriteria = new CDbCriteria();

		array_walk($data, function($val, $key) use($nav, $tags, $tagCriteria) {
			$oneNav = $nav->findByPk($val->article_nav);
			$val->article_nav = $oneNav->nav_name;

			$tagIds = explode(',', $val->article_tag);
			$tagCriteria->addInCondition('id', $tagIds);
			$tagCriteria->select = 'tag_name';
			$listTags = $tags->findAll($tagCriteria);

			// 按逗号列出其标签名
			$val->article_tag = '';

			array_walk($listTags, function($v2, $k2) use($val) {
				$val->article_tag .= $v2->tag_name.',';
			});

			$val->article_tag = mb_substr($val->article_tag, 0, -1, 'utf-8');
		});

		$this->render('index',array(
			'data'=>$data,
            'pager'=>$pager
		));
	}

	public function loadModel($id, $sec='')
	{
		$model=Article::model()->findByPk((int)$id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='article-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}

    public function getNavList()
    {
        // 获取所有栏目
        $nav = new Nav();
        $criteria = new CDbCriteria();
        $criteria->select = 'id, nav_name';
        $allNav = $nav->findAll($criteria);

        return CHtml::listData($allNav, 'id', 'nav_name');
    }

    public function getTagsList()
    {
        // 获取所有tags
        $tag = new Tags();
        $criteria = new CDbCriteria();
        $criteria->select = 'id, tag_name';
        $allTags = $tag->findAll($criteria);

        return CHtml::listData($allTags, 'id', 'tag_name');
    }


    // 上传并缩略
    private function upAndThumb($model)
    {
        $file = CUploadedFile::getInstance($model, 'article_thumbnail');
        $model->article_thumbnail = $this->getUpFileName($file);
        $file->saveAs($_SERVER["DOCUMENT_ROOT"] . DIRECTORY_SEPARATOR . $model->article_thumbnail);  // 上传图片
        BlogTool::getThumb(130, 130, $_SERVER["DOCUMENT_ROOT"] . DIRECTORY_SEPARATOR . $model->article_thumbnail, $file->getExtensionName());
    }

    // 获得上传文件名
    private function getUpFileName(CUploadedFile $up)
    {
        if(!is_dir(UPLOAD_PATH . date('Ymd')))
            mkdir(UPLOAD_PATH . date('Ymd'), 0777, true);

        return UPLOAD_PATH . date('Ymd') . '/' . time() . rand( 1 , 10000 ) . '.' . $up->getExtensionName();
    }
}
